<script setup lang="ts">
import { signInEmailService } from '@/common/services/user.service';
import { useUserStore } from '@/stores';
import { message, type FormInstance, type FormProps } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { useRequest } from 'vue-request';

defineOptions({
  name: "SignInEmail"
})

interface FormState {
  email: string | undefined,
  code: string | undefined
}


const { remainingTime, start: startCountdown, isRunning: isStartCountdown } = useCountdown()

const formState = reactive<FormState>({
  email: undefined,
  code: undefined
})

const userStore = useUserStore()

const formProps: FormProps = {
  labelCol: {
    span: 6,
  },
  labelAlign: 'left',
  wrapperCol: {
    span: 18
  },
}
const rules: Record<keyof FormState, Rule[]> = {
  email: [
    {
      required: true,
      message: "请输入您的邮箱",
    }
  ],
  code: [
    {
      required: true,
      message: "请输入验证码"
    },
    {
      len: 6,
      message: "验证码格式不正确"
    }
  ]
}

//2088486180@qq.com

const formRef = ref<FormInstance>()

const { loading: sendCodeLoading, run: sendCode } = useRequest(sendEmailCodeService, {
  onError: () => message.error("发送验证码错误,请稍后重试！"),
  onSuccess: ({ data }) => {
    if (data.code == RequestStatusCode.FAILURE) return message.error(data.message)
    startCountdown()
    message.success("发送验证码成功")
  }
})

const { loading: signInLoading, run: signIn } = useRequest(signInEmailService
  , {
    onSuccess: ({ data }) => {
      if (data.code == RequestStatusCode.FAILURE) return message.error(data.message)
      userStore.setToken(data.data)
      message.success(data.message)
    },
    onError: () => message.error("登录失败,发生错误")
  })


/**重置表单 */
const handleResetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

/**发送验证码 */
const handleSendEmailCode = async () => {
  if (!formRef.value) return
  formRef.value.validate(['email']).then(({ email }) => sendCode(email))
}

/**表单提交 */
const handleSubmit = async () => {

  if (!formRef.value) return

  // 校验表单信息并登录
  formRef.value.validate().then(({ email, code }) => {
    signIn({ email, code })
    handleResetForm()
  })

}


const isLoading = computed(() => sendCodeLoading.value || signInLoading.value)

defineExpose({
  submit: handleSubmit
})

</script>

<template>
  <div class="form-content">
    <a-spin title="加载中" :spinning="isLoading">
      <a-form :rules="rules" class="form-content-form" v-bind="{ ...formProps }" ref="formRef" :model="formState">
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入您的邮箱" />
        </a-form-item>
        <a-form-item label="验证码" name="code">
          <a-space size="middle">
            <a-input v-model:value="formState.code" placeholder="请输入验证码" :maxlength="6" />
            <a-button type="primary" @click="handleSendEmailCode" :disabled="isStartCountdown">{{ isStartCountdown ?
              `${remainingTime}秒` : "发送"
              }}</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<style scoped lang="scss">
.form {
  &-title {
    font-size: var(--text-lg);
  }

  &-content {
    display: flex;
    justify-content: center;
    flex: 1;
    padding: var(--gap-lg);
    margin-top: var(--gap-lg);
  }

  &-button {
    &--login {
      width: 100%;
    }
  }


}
</style>